﻿using System.Linq;
using System.Text.RegularExpressions;

namespace H.Utils
{

    /// <summary>
    /// 这是一个工具类,为string提供函数
    /// </summary>
    public static class StringUtil
    {
        /// <summary>
        /// 将一个驼峰命名法的标识符转换成下划线命名法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToUnderScoreCase(this string str)
        {
            return Regex.Replace(str, "([a-z])([A-Z])", "$1_$2").ToLower();
        }

        /// <summary>
        /// 将下一个下划线命名法的标识符转换为大驼峰命名法
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string ToCamelCase(this string str)
        {
            char[] chars = str.ToCharArray();

            bool first = true;
            int j = 0;
            for (int i = 0; i < chars.Length; i++)
            {
                if (chars[i] != '_')
                {
                    if (first)
                    {
                        chars[j++] = char.ToUpper(chars[i]);
                        first = false;
                    }
                    else
                    {
                        chars[j++] = chars[i];
                    }
                }
                else
                {
                    first = true;
                }
            }
            return new string(chars.Take(j).ToArray());
        }


        /// <summary>
        /// 切割一个字符串为数字数组
        /// </summary>
        /// <param name="value">需要被分割的字符串</param>
        /// <param name="count">字符串被分割的份数,不符合则会切分失败</param>
        /// <param name="result">返回数字的缓冲区,如果空间不够,则自动分配一个更大的缓冲区</param>
        /// <param name="spliters">分隔符</param>
        /// <returns>如果切割成功,则返回true,并在result中存储结果</returns>
        public static bool SplitAsInt(this string value, int count, ref int[] result, params char[] spliters)
        {
            string[] values = value.Split(spliters);
            if (values.Length == count)
            {
                if (result.Length < count)
                {
                    result = new int[count];
                }

                for (int i = 0; i < count; i++)
                {
                    if (!int.TryParse(values[i], out result[i]))
                    {
                        return false;
                    }
                }
                return true;
            }
            return false;
        }
    }
}
